/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rw.magallanes.utilities;

import com.rw.magallanes.core.Category;
import com.rw.magallanes.core.Item;
import com.rw.magallanes.core.Warehouse;
import com.rw.magallanes.db.StorageException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.StringTokenizer;

/**
 *
 * @author Gonzalez
 */
public class InventoryReader {

    private File file = new File("D:\\Trauco\\magallanes\\dev\\inventario.txt");

    public void read() throws FileNotFoundException, IOException, StorageException {
        Warehouse wh = Utilities.loadWarehouse();
        wh.clear();

        FileInputStream fis = new FileInputStream(file);
//        InputStreamReader isr = new InputStreamReader(fis, Charset.forName("ISO-8859-1"));
//        InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
        InputStreamReader isr = new InputStreamReader(fis, Charset.forName("windows-1252"));
        BufferedReader br = new BufferedReader(isr);
        String line = "";

        while ((line = br.readLine()) != null) {
            StringTokenizer st = new StringTokenizer(line, ";");
            String categoryName = st.nextToken();
            String itemName = st.nextToken();

            if (!wh.existsCategoryName(categoryName)) {
                wh.addCategory(new Category(categoryName));
            }

            if (wh.existsItemName(itemName)) {
                throw new RuntimeException("El item ya existe: " + itemName);
            }

            Category category = wh.getCategory(categoryName);
            Item item = new Item(itemName, category, 0);
            category.addItem(item);
        }

        wh.save();
    }

    public static void main(String[] args) {
        try {
            InventoryReader reader = new InventoryReader();
            reader.read();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
